//
//  ViewController.m
//  LeoAesOCDemo
//
//  Created by leo on 2020/10/15.
//  Copyright © 2020 leo. All rights reserved.
//

#import "ViewController.h"
#import "FHAes.h"

static const int kAesKeySize = 256;

@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    // 网上找的aes256库，都是需要自己设置pkcs7padding，这里是经过验证的方法，便于参考。
}

void encrypt_aes256_cbc_pkcs7padding() {
    // 这里应该是需要加密的数据
    NSData *data = [NSData data];
    NSUInteger len = data.length;
    const char* psrc = (const char*)data.bytes;
    
    // 32位加密秘钥
    NSString *secretKey = @"12345678123456781234567812345678";
    const BYTE *key = (const BYTE *)[secretKey cStringUsingEncoding:NSUTF8StringEncoding];
    
    // 16位向量iv
    unsigned char iv[AES_BLOCK_SIZE] = { 0 };
    for (int i = 0; i < AES_BLOCK_SIZE; ++i) {
        iv[i] = key[i];
    }

    unsigned int key_schedule[AES_BLOCK_SIZE * 8] = { 0 };
    aes_key_setup(key, key_schedule, kAesKeySize);
    
    // 使用pkcs7padding 计算padding_len
    int r = len % AES_BLOCK_SIZE;
    int padding_len = AES_BLOCK_SIZE - r;
    int src_len = len + padding_len;

    auto src = (unsigned char*)malloc((src_len + 1) * sizeof(char));
    memset(src, 0, src_len);
    memcpy(src, psrc, len);
    if (padding_len > 0) {
        // 使用pkcs7padding 填充padding_len
        memset(src + len, (unsigned char)padding_len, padding_len);
    }
    
    //
    auto output = (unsigned char*)malloc((src_len + 1)* sizeof(char));
    memset(output, src_len, 0);

    aes_encrypt_cbc(src, src_len, output, key_schedule, kAesKeySize, iv);

    free(output);
    free(src);
}

void decrypt_aes256_cbc_pkcs7padding() {
    // 这里应该是加密过的数据，我在这随便写的
    NSData *data = [NSData data];
    NSUInteger len = data.length;
    const char* psrc = (const char*)data.bytes;
    
    // 32位加密秘钥
    NSString *secretKey = @"12345678123456781234567812345678";
    const BYTE *key = (const BYTE *)[secretKey cStringUsingEncoding:NSUTF8StringEncoding];
    
    // 16位向量iv
    unsigned char iv[AES_BLOCK_SIZE] = { 0 };
    for (int i = 0; i < AES_BLOCK_SIZE; ++i) {
        iv[i] = key[i];
    }

    unsigned int key_schedule[AES_BLOCK_SIZE * 8] = { 0 };
    aes_key_setup(key, key_schedule, kAesKeySize);
    
    auto src = (unsigned char*)malloc((len + 1) * sizeof(char));
    memset(src, 0, len);
    memcpy(src, psrc, len);
    
    auto output = (unsigned char*)malloc((len + 1)* sizeof(char));
    memset(output, len, 0);
    aes_decrypt_cbc((unsigned char*)src, len, (unsigned char*)output,
                    key_schedule, kAesKeySize, iv);
    
    unsigned int r = output[len - 1];
    int dst_len = len - r;
    
    free(output);
    free(src);
}

@end
